﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ZhCun.Utils;

namespace ZhCun.WebUtils
{
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                HttpMonitor.OnRequest(context.Request);

                await next.Invoke(context);

                HttpMonitor.OnResponse(context.Response);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }


        private async Task HandleExceptionAsync(HttpContext context, Exception e)
        {            
            string ip = context.Connection.RemoteIpAddress.ToString();
            LogHelper.LogObj.Fatal($"IP:{ip},发生错误 ", e);

            //记日志

            //int sysId = 1;
            
            //logger.LogError($"系统编号：{sysId},主机IP:{ip},堆栈信息：{e.StackTrace},异常描述：{e.Message}");
           // string result = System.Text.Json.JsonSerializer.Serialize(ResultBody.error(e.Message));
            //await context.Response.WriteAsync(result);
        }
    }
}
